package operation_system.producer_consumer;

import java.util.ArrayList;
import java.util.List;

public class AMethod {
    public static void main(String[] args) {
        Storage storage = new Storage(new ArrayList<>());
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                while (true) {
                    try {
                        Thread.sleep(2000);
                        storage.produce();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }
        for (int i = 0; i < 1; i++) {
            new Thread(()->{
                while (true) {
                    try {
                        Thread.sleep(2000);
                        storage.consume();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }
    }
}
//队列空或满会把在锁上等待的所有线程唤醒，没有细粒度的控制，效率低
class Storage{
    private List<Object> list = new ArrayList<>();
    private static final int MAX_SIZE = 10;
    public Storage(List<Object> list) {
        this.list = list;
    }
    public void produce(){
        synchronized (list) {
            while (list.size() + 1 > MAX_SIZE) {
                try {
                    System.out.printf("生产者：%s，仓库已满！\n", Thread.currentThread().getName());
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "生产了一件！");
            list.add(new Object());
            list.notifyAll();

        }
    }

    public void consume(){
        synchronized (list) {
            while (list.size() == 0) {
                try {
                    System.out.printf("消费者：%s，仓库为空！\n", Thread.currentThread().getName());
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            list.remove(list.size() - 1);
            System.out.println(Thread.currentThread().getName() + "消费了一件！");
            list.notifyAll();
        }
    }
}